package at.fhj.pse.domain.service;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import at.fhj.pse.domain.exception.DomainLayerException;

public class SecurePassword {
	
	private String secPassword;
	
	public SecurePassword(String password) {
		this.secPassword = securePassword(password);
	}

	private String securePassword(String password) {
		if (password == null) {
			throw new DomainLayerException("password is null", new IllegalArgumentException());
		}
		try {
			// Create MessageDigest instance for MD5
			MessageDigest md = MessageDigest.getInstance("MD5");
			// Add password bytes to digest
			md.update(password.getBytes());
			// Get the hash's bytes
			byte[] bytes = md.digest();
			// This bytes[] has bytes in decimal format;
			// Convert it to hexadecimal format
			StringBuilder sb = new StringBuilder();
			for (int i = 0; i < bytes.length; i++) {
				sb.append(Integer.toString((bytes[i] & 0xff) + 0x100, 16)
						.substring(1));
			}
			// Get complete hashed password in hex format
			return (sb.toString());
		} catch (NoSuchAlgorithmException ex) {
			throw new DomainLayerException("no such algorithm", ex);
		}
	}

	public String getSecPassword() {
		return secPassword;
	}

}